import requests
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse
from . import forms
from .forms import RegistForm, CenterForm
# from .forms import RegistForm, CenterForm

from .models import CustomUser, WeiBoUser
from django.contrib.auth.views import auth_login, auth_logout, login_required


# Create your views here.
def login(request):
    lgf = forms.LoginForm()
    errors = None
    if request.method == "POST":
        lgf = forms.LoginForm(data=request.POST)
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = CustomUser.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth_login(request, user)
                next_url = request.GET.get("next")
                if next_url:
                    return redirect(to=next_url)
                else:
                    return redirect(to=reverse("main:index"))
            else:
                errors = "密码错误"
        else:
            errors = "用户名不存在"
    return render(request, "user/login.html", context={"errors": errors, "lgf": lgf})


def regist(request):
    rgf = forms.RegistForm()
    errors = ""
    if request.method == "POST":
        rgf = RegistForm(request.POST)
        if rgf.is_valid():
            password2 = rgf.cleaned_data.pop("password2")
            password = rgf.cleaned_data.pop("password")
            if password != password2:
                errors = "密码不一致"
            else:
                user = rgf.save(commit=False)
                user.password = make_password(password)
                user.save()
                auth_login(request, user)
                return redirect(to=reverse("main:index"))
    return render(request, "user/regist.html", context={"rgf": rgf, "errors": errors})


@login_required
def center(request):
    cf = CenterForm(initial={
        "username": request.user.username,
        "email": request.user.email,
        "telephone": request.user.telephone,
        "first_name": request.user.first_name,
        "last_name": request.user.last_name,
    })
    if request.method == "POST":
        # data 确定 表单传入数据 #instance 确定原始数据
        cf = CenterForm(data=request.POST, files=request.FILES, instance=request.user)
        if cf.is_valid():
            cf.save()
            return redirect(to=reverse("user:center"))
    return render(request, "user/center.html", context={"cf": cf})


def logout(request):
    auth_logout(request)
    return redirect(to=reverse("main:index"))


@login_required
def updatepassword(request):
    upf = forms.UpdatePasswordForm(request.POST)
    errors = None
    password0 = request.POST.get("password0")
    password1 = request.POST.get("password1")
    password2 = request.POST.get("password2")
    if not request.user.check_password(password0):
        errors = "原始密码错误"
    else:
        if password1 != password2:
            errors = "密码不一致"
        else:
            request.user.set_password(password1)
            request.user.save()
            auth_logout(request)

            return redirect(to=reverse("user:login"))

    return render(request, "user/updatepassword.html", context={"errors": errors, "upf": upf})


def chcheck_username(request):
    username = request.GET.get("username")
    if CustomUser.objects.filter(username=username).exists():
        return JsonResponse({
            "code": 0,
            "msg": "成功"
        })
    else:
        return JsonResponse({
            "code": -1001,
            "msg": "用户名不存在"
        })


def auth(request):
    code = request.GET.get("code")
    data = {
        "client_id": "3223537156",
        "client_secret": "a0ba41acf92dd5d1d0c83be6321d4fda",
        "grant_type ": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/user/auth",
    }

    res = request.post("https://api.weibo.com/oauth2/access_token", data=data)
    uid = res.json()['uid']
    print(uid)

    wb_user = WeiBoUser.objects.filter(uid).first()
    if wb_user:
        user = wb_user.cu
        auth_login(request, user)
    else:
        user = CustomUser.objects.create_user(username=f"微博_{uid}", password="123456")
        wb_user = WeiBoUser()
        wb_user.uid = uid
        wb_user.cu = user
        wb_user.save()

    auth_login(request, user)
    return redirect(to=reverse("main:index"))


    # token = res.json()['access_token']
    #
    # data2 = {
    #     "access_token": token
    # }
    #
    # res2 = requests.post("https://api.weibo.com/oauth2/get_token_info", data=data2)
    # print(res2.json())

    # return JsonResponse({
    #     "code": 0,
    #     "msg": "用户名不存在"
    # })


"""
1.微博开放平台开发者认证
2.创建应用
3.基本信息:获取appkey 和app-secret
4.测试信息: 添加测试账号
5.高级信息添加回调地址
6. 查看文档 web网站 OAuth2.0授权, 与微博登录组件.
理解每一个接口的作用
接口一
https
dd053    每次都不一样
接口二
https://api.weibo.com/oauth2/access_token
access_token 2.009....  有效期内不变
uid 1690457060 核心信息 每一个新浪微博唯一信息
接口三
"""